<?php

// 生成 RSA 密钥对
$config = array(
    "private_key_bits" => 2048,
    "private_key_type" => OPENSSL_KEYTYPE_RSA,
);

// 创建新的密钥对
$res = openssl_pkey_new($config);

// 获取私钥
openssl_pkey_export($res, $privateKey);

// 获取公钥
$publicKey = openssl_pkey_get_details($res);
$publicKey = $publicKey["key"];

// 保存私钥到文件
file_put_contents('private_key.pem', $privateKey);

// 保存公钥到文件（通常公钥会嵌入到证书中，这里仅作为示例）
file_put_contents('public_key.pem', $publicKey);

// 待签名的数据
$dataToSign = "Hello, this is a test message for RSAwithSHA256 signing.";

// 使用私钥进行签名
$signature = '';
openssl_sign($dataToSign, $signature, $privateKey, 'sha256WithRSAEncryption');

// 将签名转换为 Base64 编码的字符串
$signatureBase64 = base64_encode($signature);

echo "Original Data: " . $dataToSign . "\n";
echo "Signature (Base64): " . $signatureBase64 . "\n";

// 验证签名（这里仅展示如何设置验证，实际验证需要使用公钥）
$valid = openssl_verify($dataToSign, base64_decode($signatureBase64), $publicKey, 'sha256WithRSAEncryption');

if ($valid === 1) {
    echo "Signature is valid.\n";
} elseif ($valid === 0) {
    echo "Signature is invalid.\n";
} else {
    echo "Error in signature verification.\n";
}

// 清理资源
openssl_free_key($res);

?>